﻿using AppDataStruct;
using ComLib.ComFun;
using ComUIControl;
using KCommon;
using KWindow.KPageCore;
using LogLib;
using Microsoft.Ink;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace YSLPages
{
    public partial class PageSignature : PageControlBase
    {
        private PreApplyInfo _appInfo = null;

        private string _ywbh = "";

        private SFZInfo _sfz = new SFZInfo();

        //private string _fileName = "";

        private const string _tipsContent = "签名完成后请点击确认按钮";

        private const string _tipsTitle = "请使用触笔在指定区域签名";

        private string _zipFile = "";

        private string _signatureImageFile = "";

        private bool _bSignature = false;  //是否采集了签名

        private DeviceControl _device = null;

        private AppDirectory appDirs = new AppDirectory();

        private SignatureOption _option = new SignatureOption();

        /// <summary>
        /// 清空签名按钮
        /// </summary>
        private Button buttonClear = null;

        private Microsoft.Ink.InkPicture pbxSignature = null;
        public PageSignature()
        {
            InitializeComponent();
            SetProcessBase(ProcessSignature.Instance);
        }

        private void LoadOption()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            buttonClear = GetControl<Button>("buttonClear") as Button;
            pbxSignature = GetControl<Microsoft.Ink.InkPicture>("pbxSignature") as Microsoft.Ink.InkPicture;
            SetButtonDefaultStyles(buttonClear);
            if (!IsMainPage)
            {
                pbxSignature.Stroke += (s, e) =>
                {
                    //lock (_lock)
                    //{
                        Process.SetValue("SXQM", pbxSignature);
                        //Log.WriteAsync($"设置签名值:{pbxSignature}");
                    //}
                };
            }
        }

        //private object _lock = new object();
        //private Thread _threadUpdateSignatureImage = null;
        //private bool _threadExit = false;
        //private void UpdateSignatureImage()
        //{
        //    while (!_threadExit)
        //    {
        //        try
        //        {
        //            lock (_lock)
        //            {
        //                Microsoft.Ink.InkPicture inkSXQM = Process.GetValue<Microsoft.Ink.InkPicture>("SXQM");
        //                if (null != inkSXQM && inkSXQM.Ink.Strokes.Count > 0)
        //                {
        //                    pbxSignature.BeginInvoke(new Action(() =>
        //                    {
        //                        Bitmap bitmap = new Bitmap(pbxSignature.Width, pbxSignature.Height);
        //                        using (Graphics g = Graphics.FromImage(bitmap))
        //                        {
        //                            if (pbxSignature.Image != null)
        //                            {
        //                                pbxSignature.Image.Dispose();
        //                                pbxSignature.Image = null;
        //                            }
        //                            pbxSignature.Renderer.Draw(g, inkSXQM.Ink.Strokes);
        //                            pbxSignature.Image = bitmap;
        //                        }
        //                    }));
        //                }
        //            }                    
        //        }
        //        catch
        //        {

        //        }
        //        Thread.Sleep(20);
        //    }
        //}

        private void buttonClear_Click(object sender, EventArgs e)
        {
            if (null != pbxSignature)
            {
                pbxSignature.Ink.DeleteStrokes();
                pbxSignature.Refresh();
                Process.SetValue("SXQM", pbxSignature);
                Log.WriteAsync($"清空签名:{pbxSignature}");
            }
        }

        //初始化窗体数据
        public override void InitData()
        {
            base.InitData();
            LoadOption();
            _bSignature = false;
            _signatureImageFile = "";

            _appInfo = Process.GetValue<PreApplyInfo>("PreApplyInfo");
            _signatureImageFile = string.Format(@"{0}\{1}.bmp", appDirs.Signature, _appInfo.SFZH);
            _zipFile = string.Format(@"{0}\{1}.zip", appDirs.Signature, _appInfo.SFZH); ;
            _sfz = Process.GetValue<SFZInfo>("SFZInfo");
            if (_appInfo != null)
            {
                _ywbh = _appInfo.HZSQ.YWBH;
            }
            if (string.IsNullOrEmpty(_ywbh))
            {
                _ywbh = _sfz.SFZH;
            }
            if (_option.SignType == 0)
            {
                Speak("请使用笔触在下方的签名板上签名");
                _device = new DeviceControl("TopCamera");
                _device.OnCatchException = OnCatchException;
                _device.OnWorkingDone = OnCapSuccess;
                _device.OnWorkingFailed = OnCapFailed;
                _device.OnTimeout = OnCapTimeout;
                _device.Init();
            }
            else if (_option.SignType == 2)
            {
                //if (IsMainPage)
                //{
                //    _threadUpdateSignatureImage = new Thread(UpdateSignatureImage);
                //    _threadUpdateSignatureImage.IsBackground = true;
                //    _threadUpdateSignatureImage.Start();
                //}
            }
            else  //wacom == 1
            {
                _device = new DeviceControl("SignatureBoard");
                _device.OnCatchException = OnCatchException;
                _device.OnWorkingDone = OnCapSuccess;
                _device.OnWorkingFailed = OnCapFailed;
                _device.OnTimeout = OnCapTimeout;
                _device.Init();
            }
        }

        private void OnCapTimeout(string outParams)
        {
            Log.WriteAsync(string.Format("OnCapTimeout：{0}", outParams));
        }

        private void OnCapFailed(string outParams, string error)
        {
            Log.WriteAsync(string.Format("OnCapFailed：{0}", error));
            if (_option.SignType == 1)
            {
                string msg = string.Format("签名失败: \n{0}", error);
                Log.WriteAsync(msg);
                ClearData();
                Process.ToHome();
            }
        }

        private void OnCapSuccess(string outParams)
        {
            if (_option.SignType == 1)
            {
                _bSignature = true;
                Log.WriteAsync("签名成功");
                UpdateData();
                ClearData();
                if (_config.WorkFlow.ReceiveWay)
                {
                    Process.ToNext();
                }
                else
                {
                    Process.ToAny("YSLPages.PagePreviewChecking");
                }
            }
        }

        private void OnCatchException(string outParams)
        {
            Log.WriteAsync(string.Format("OnCatchException：{0}", outParams));
            if (_option.SignType == 1)
            {
                string msg = string.Format("设备运行发生了异常: \n{0}", outParams);
                Log.WriteAsync(msg);
                Action<string> handler = (e) =>
                {
                    MessageBox.Show(e);
                    ClearData();
                    Process.ToHome();
                };
                this.Invoke(handler, msg);
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            if (_option.SignType == 0)
            {
                if (_bSignature && _appInfo != null)
                {
                    _appInfo.SXQM_ZIP = _zipFile;
                    _appInfo.HZSQ.SXQM = _signatureImageFile;
                }
            }
            else if (_option.SignType == 1)
            {
                string msg = "";
                if (SignatureFun.MakeSignatureZipFile(_signatureImageFile, _zipFile, out msg))
                {
                    //Process.SetValue("SignatureImage", _signatureImageFile);
                    //Process.SetValue("SignaturePhotoPath", _signatureImageFile);
                    _appInfo.SXQM_ZIP = _zipFile;
                    _appInfo.HZSQ.SXQM = _signatureImageFile;
                }
                else
                {
                    Log.WriteAsync("生成签名文件失败:" + msg);
                    MsgBox.Show("生成签名文件失败:" + msg);
                    Process.ToHome();
                }

            }
            else
            {
                if (_appInfo != null)
                {
                    _appInfo.SXQM_ZIP = _zipFile;
                    _appInfo.HZSQ.SXQM = _signatureImageFile;
                }
            }

            Log.WriteAsync("进入下一页");
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            //清空之前的笔迹
            buttonClear_Click(null, null);
            if (_device != null)
            {
                _device.Stop();
                _device.Dispose();
                _device = null;
            }
            //_threadExit = true;
            //if (null != _threadUpdateSignatureImage)
            //{
            //    _threadUpdateSignatureImage.Join();
            //}
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {
            base.Close();
        }

        public override void StartWork()
        {
            base.StartWork();
            Speak("请使用屏幕下方的签字笔，在签名板上使用正楷字体签字。签字完成后，点击签名板上的确定按钮");
            string personDataDir = Process.GetValue<string>("PersonDataDirectory");
            if (_option.SignType == 0)  //弹窗的方式
            {
                frmSignatureCustom frm = new frmSignatureCustom(personDataDir, _ywbh);
                _device.Do();
                if (frm.ShowDialog(this) == DialogResult.OK)
                {
                    Log.WriteAsync("签名完成，进入下一步.");
                    _zipFile = frm.strZipFile;
                    _signatureImageFile = frm.strImgFile;
                    _bSignature = true;
                    UpdateData();
                    ClearData();

                }
                else
                {
                    //MessageBox.Show(frm.strMessage);
                    Log.WriteAsync(string.Format("取消签名,[{0}]", frm.strMessage));
                    _bSignature = false;
                    //ClearData();
                    //Process.ToHome();
                }
                StopCountdown();
                if (_config.WorkFlow.ReceiveWay)
                {
                    Process.ToNext();
                }
                else
                {
                    Process.ToAny("YSLPages.PagePreviewChecking");
                }
            }
            else if (_option.SignType == 2)  //在界面上集成了picture
            {
                _bSignature = true;
            }
            else   //Wacom
            {
                KCommon.CallBackIn param = new KCommon.CallBackIn();//"SignatureBoard", "DOPERSO"
                param["ImageFile"] = _signatureImageFile;
                param["TipsContent"] = _tipsContent;
                param["TipsTitle"] = _tipsTitle;
                string data = param.ToString();
                Log.WriteAsync(data);
                _device.Start(data);
            }

        }

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            base.OnCountdownCompleted(sender, e);
        }

        protected override void btnBack_Click(object sender, EventArgs e)
        {
            base.btnBack_Click(sender, e);
        }

        private bool MakeSignatureFile()
        {
            try
            {
                //Rectangle inkBox = pbxSignature.Ink.GetBoundingBox();
                //Point point = new Point(inkBox.Left, inkBox.Top);
                //Graphics tempGraphics = CreateGraphics();
                //Microsoft.Ink.Renderer inkRenderer = new Renderer();
                //inkRenderer.InkSpaceToPixel(tempGraphics, ref point);
                //tempGraphics.Dispose();
                if (File.Exists(_signatureImageFile))
                    File.Delete(_signatureImageFile);

                if (File.Exists(_zipFile))
                    File.Delete(_zipFile);

                Microsoft.Ink.InkPicture inkSXQM = Process.GetValue<Microsoft.Ink.InkPicture>("SXQM");
                if (null != inkSXQM && inkSXQM.Ink.Strokes.Count > 0)
                {
                    byte[] bytes = inkSXQM.Ink.Save(PersistenceFormat.Gif, CompressionMode.NoCompression);
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        //string strBmpFileName = Path.Combine(_saveDir, _strYwbh + ".bmp");
                        //string strZipFileName = Path.Combine(_saveDir, _strYwbh + ".zip");



                        Bitmap gif = new Bitmap(ms);

                        gif.Save(_signatureImageFile, ImageFormat.Bmp);    //转成bmp                  

                        byte[] scr = IPCCom.ReadByteArray(_signatureImageFile);

                        int outZipLength = 0;
                        int outBufLength = scr.Length + 10;

                        byte[] outBuffer = new byte[outBufLength];

                        int nRes = SegSignature.SegmentSignature_Mem(scr, scr.Length, outBuffer, outBufLength, ref outZipLength);
                        if (1 == nRes)
                        {
                            IPCCom.ByteToDat(outBuffer, outZipLength, _zipFile);
                            return true;
                        }
                        else
                        {
                            MsgBox.Show("生成签名失败！请尝试重新签名。代码:" + nRes.ToString());
                            return false;
                        }
                    }
                }
                else
                {
                    if (IsMainPage)
                    {
                        if (null == inkSXQM)
                        {
                            Log.WriteAsync("主屏：inkSXQM为空");
                        }
                        else
                        {
                            if (inkSXQM.Ink.Strokes.Count == 0)
                            {
                                Log.WriteAsync($"主屏：inkSXQM.Ink.Strokes.Count={inkSXQM.Ink.Strokes.Count}");
                            }
                        }

                    }
                    else
                    {
                        if (null == inkSXQM)
                        {
                            Log.WriteAsync("副屏：inkSXQM为空");
                        }
                        else
                        {
                            if (inkSXQM.Ink.Strokes.Count == 0)
                            {
                                Log.WriteAsync($"副屏：inkSXQM.Ink.Strokes.Count={inkSXQM.Ink.Strokes.Count}");
                            }
                        }
                    }
                    var dr = MessageBoxS.Show("", "签名为空，是否跳过签名？");
                    if (dr == DialogResult.Yes)
                    {
                        Log.WriteAsync("跳过签名");
                        return true;
                    }

                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                MsgBox.Show($"签名异常[{ex.Message}]，请重新签名");
                return false;
            }
            finally
            {
                //SD.Remove("SXQM");
            }
        }

        protected override void btnNext_Click(object sender, EventArgs e)
        {
            bool ret = true;
            if (_option.SignType == 2)
            {
                ret = MakeSignatureFile();
            }
            else if (!_bSignature)
            {
                MessageBox.Show("请注意: 签名操作已取消，未采集成功.");
            }
            if (ret)
            {
                UpdateData();
                ClearData();
                //Process.ToNext();
                if (_config.WorkFlow.ReceiveWay)
                {
                    Process.ToNext();
                }
                else
                {
                    Process.ToAny("YSLPages.PagePreviewChecking");
                }
            }
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            base.btnCancel_Click(sender, e);
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            Process.ToNext();
        }
    }
}
